package com.company.algo.complicateStruct.cacheStruct.lru;

import java.util.LinkedHashMap;

public class LRUCache {
    private LinkedHashMap<Integer,Integer> cache;
    private int cap;

    public LRUCache(int capability){
        this.cap = capability;
        this.cache = new LinkedHashMap<>();
    }

    private void makeRecently(int key){
        int val = cache.get(key);
        cache.remove(key);
        cache.put(key,val);
    }

    public int get(int key){
        if (!cache.containsKey(key)) return -1;
        makeRecently(key);
        return cache.get(key);
    }

    public void put(int key, int val){
        if (cache.containsKey(key)) {
            cache.put(key,val);
            makeRecently(key);
            return;
        }
        if (cache.size()>=cap){
            int oldestKey = cache.keySet().iterator().next();
            cache.remove(oldestKey);
        }
        cache.put(key,val);
    }
}
